// LoadingService.js
import React from "react";
import { createRef,  } from "react";
import {View, StyleSheet, Text, ActivityIndicator} from 'react-native';
import Spinner from "react-native-loading-spinner-overlay";

class LoadingService {
    spinnerRef = createRef();

    show(message = "加载中...") {
        console.log('hello')
        if (this.spinnerRef.current) {
            this.spinnerRef.current.show(message);
        }
    }

    hide() {
        if (this.spinnerRef.current) {
            this.spinnerRef.current.hide();
        }
    }
}

export const loadingService = new LoadingService();

export const LoadingOverlay = React.forwardRef((props, ref) => {
    const [visible, setVisible] = React.useState(false);
    const [message, setMessage] = React.useState("");

    React.useImperativeHandle(ref, () => ({
        show: (msg) => {
            setMessage(msg || "加载中...");
            setVisible(true);
        },
        hide: () => {
            setVisible(false);
        },
    }));

    return (
        visible && (
            <View style={styles.overlay}>
                <View style={styles.container}>
                    <ActivityIndicator size="large" color="#fff" />
                    <Text style={styles.text}>{message}</Text>
                </View>
            </View>
        )
    );
});


const styles = StyleSheet.create({
    overlay: {
        position: "absolute",
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        // backgroundColor: "rgba(0, 0, 0, 0.5)", // 半透明背景
        justifyContent: "center",
        alignItems: "center",
        zIndex: 1000,
    },
    container: {
        backgroundColor: "rgba(0, 0, 0, 0.8)", // 深色背景容器
        borderRadius: 8,
        padding: 20,
        justifyContent: "center",
        alignItems: "center",
        minWidth: 100,
    },
    text: {
        color: "#fff",
        fontSize: 14,
        marginTop: 10,
    },
});
